package com.file;

import com.google.gson.Gson;
import com.google.gson.JsonObject;

import javax.sound.sampled.*;
import java.io.*;
import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.Scanner;

public class Test {
    private static final float SAMPLE_RATE = 44100;
    private static final int SAMPLE_SIZE = 16;
    private static final int CHANNELS = 1;
    private static final long RECORD_DURATION = 10000; // 10秒
    private static final long PAUSE_DURATION = 60000; // 1分钟

    public static void main(String[] args) throws Exception {
        AudioFormat format = new AudioFormat(SAMPLE_RATE, SAMPLE_SIZE, CHANNELS, true, true);
        DataLine.Info info = new DataLine.Info(TargetDataLine.class, format);

        try (TargetDataLine line = (TargetDataLine) AudioSystem.getLine(info)) {
            line.open(format);
            line.start();

            Scanner scanner = new Scanner(System.in); // 用于接收用户输入

            while (true) {
                System.out.println("开始录音...");
                ByteArrayOutputStream out = new ByteArrayOutputStream();
                byte[] buffer = new byte[4096];

                long startTime = System.currentTimeMillis();
                while (System.currentTimeMillis() - startTime < RECORD_DURATION) {
                    int bytesRead = line.read(buffer, 0, buffer.length);
                    if (bytesRead > 0) {
                        out.write(buffer, 0, bytesRead);
                    }
                }

                System.out.println("停止录音");
                File audioFile = saveToFile(out.toByteArray(), format);

                // 等待用户输入"start"
                System.out.println("录音已保存，路径为：" + audioFile.getAbsolutePath());
                System.out.println("请检查录音文件是否正确，然后输入'start'继续发送：");
                String userInput = scanner.nextLine().trim();

                while (!userInput.equalsIgnoreCase("start")) {
                    System.out.println("输入无效，请输入'start'继续发送：");
                    userInput = scanner.nextLine().trim();
                }

                // 用户确认后发送文件路径
                sendToAPI(audioFile);

                System.out.println("暂停1分钟...");
                Thread.sleep(PAUSE_DURATION);
            }
        }
    }

    private static File saveToFile(byte[] audioData, AudioFormat format) throws IOException {
        // 指定保存路径
        Path savePath = Paths.get("E:/develop/code/learnjava/FileOperations/src/main/resources/audio");
        if (!Files.exists(savePath)) {
            Files.createDirectories(savePath); // 如果目录不存在，则创建
        }

        // 创建唯一文件名
        File audioFile = new File(savePath.toFile(),  System.currentTimeMillis() + ".wav");

        try (AudioInputStream stream = new AudioInputStream(
                new ByteArrayInputStream(audioData),
                format,
                audioData.length / format.getFrameSize())) {

            AudioSystem.write(stream, AudioFileFormat.Type.WAVE, audioFile);
        }
        return audioFile;
    }

    private static void sendToAPI(File audioFile) {
        HttpClient client = HttpClient.newHttpClient();

        // 构造包含文件路径的JSON对象
        JsonObject jsonBodyObj = new JsonObject();
        jsonBodyObj.addProperty("file_path", audioFile.getAbsolutePath());

        Gson gson = new Gson();
        String jsonBody = gson.toJson(jsonBodyObj);
        System.out.println(jsonBody);

        // 创建HTTP请求
        HttpRequest request = HttpRequest.newBuilder()
                .uri(URI.create("http://localhost:8000/recognize/file"))
                .header("Content-Type", "application/json")
                .POST(HttpRequest.BodyPublishers.ofString(jsonBody))
                .build();

        // 发送请求并处理响应
        try {
            HttpResponse<String> response = client.send(request, HttpResponse.BodyHandlers.ofString());
            if (response.statusCode() == 200) {
                System.out.println("响应数据：" + response.body());
            } else {
                System.err.println("API请求失败，状态码：" + response.statusCode());
            }
        } catch (Exception e) {
            System.err.println("API请求失败：" + e.getMessage());
        }
    }
}